package cqrtplm.util;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;

@Component
@Slf4j
public class OrderNumberGenerator {
    // 字母序列（去除 O, Q, I）
    private static final String LETTERS = "ABCDEFGHJKLMNPRSTUVWXYZ";
    private static final int LETTER_BASE = LETTERS.length();

    // 产品线计数器（产品线编码 -> 计数器）
    private final ConcurrentMap<String, AtomicInteger> counters = new ConcurrentHashMap<>();

    /**
     * 生成下一个流水号
     *
     * @param currentMaxSequence 当前最大流水号（不带产品线编码的部分）
     * @return 下一个流水号
     */
    public static String generateNextSequence(String currentMaxSequence) {
        // 1. 转换当前序列值为整数
        int currentValue = convertSequenceToValue(currentMaxSequence);

        // 2. 计算下一个序列值
        int nextValue = currentValue + 1;

        // 3. 转换为2位流水号
        return convertValueToSequence(nextValue);
    }

    /**
     * 将流水号转换为序列值
     */
    private static int convertSequenceToValue(String sequence) {
        if (sequence == null || sequence.isEmpty()) {
            return -1; // 初始值
        }

        // 数字序列 (00-99)
        if (sequence.matches("\\d{2}")) {
            return Integer.parseInt(sequence);
        }

        // 字母序列 (AA-ZZ)
        if (sequence.matches("[A-Z]{2}")) {
            char firstChar = sequence.charAt(0);
            char secondChar = sequence.charAt(1);

            int firstIndex = LETTERS.indexOf(firstChar);
            int secondIndex = LETTERS.indexOf(secondChar);

            if (firstIndex == -1 || secondIndex == -1) {
                throw new IllegalArgumentException("无效的序列号: " + sequence);
            }

            return 100 + (firstIndex * LETTER_BASE + secondIndex);
        }

        throw new IllegalArgumentException("无效的序列号格式: " + sequence);
    }

    /**
     * 将序列值转换为2位流水号
     */
    private static String convertValueToSequence(int value) {
        if (value < 0) {
            return "00"; // 初始值
        }

        if (value < 100) {
            // 数字模式 (00-99)
            return String.format("%02d", value);
        } else {
            // 字母模式 (AA-ZZ)
            int adjustedValue = value - 100;
            if (adjustedValue >= LETTER_BASE * LETTER_BASE) {
                throw new IllegalStateException("流水号已用完");
            }

            int firstCharIdx = adjustedValue / LETTER_BASE;
            int secondCharIdx = adjustedValue % LETTER_BASE;

            return String.valueOf(LETTERS.charAt(firstCharIdx))
                    + LETTERS.charAt(secondCharIdx);
        }
    }
}
